const os = require('os');
const path = require('path');
const interfaces = os.networkInterfaces();
const { defineConfig } = require('@vue/cli-service');
const mocksServer = require('./mocks/mocks-server.js');

function hostIp() {
  let IPv4 = null;
  if (process.platform === 'darwin') {
    // Mac平台
    for (let i = 0; i < interfaces.en0.length; i++) {
      if (interfaces.en0[i].family === 'IPv4') {
        IPv4 = interfaces.en0[i].address;
      }
    }
  } else if (process.platform === 'win32') {
    // windows平台
    for (const devName in interfaces) {
      const iface = interfaces[devName];
      for (let i = 0; i < iface.length; i++) {
        const alias = iface[i];
        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
          IPv4 = alias.address;
        }
      }
    }
  }
  return IPv4;
}
function resolve(dir) {
  return path.join(__dirname, '.', dir);
}
function isDevFn() {
  return process.env.NODE_ENV === 'development';
}
const isDev = isDevFn();

module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: isDev ? '/' : '',
  outputDir: 'dist', // 输出文件目录
  lintOnSave: isDev ? 'error' : false, // true, false, error, warning, default
  configureWebpack: {
    devtool: 'cheap-module-source-map',
    resolve: {
      alias: {
        mocks: resolve('mocks'),
        static: resolve('public/static'),
        '@': resolve('src'), // 默认已配置
        assets: resolve('src/assets'),
        constantDic: resolve('src/constantDic')
      }
    },
    plugins: []
  },
  chainWebpack: (config) => {
    config.module.rule('svg').exclude.add(resolve('src/icons')).end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      });
  },
  // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建
  productionSourceMap: false,
  devServer: {
    // host设置为'0.0.0.0'即可开启一个本地ip的服务，可以分享给其它人看，也可以npm run dev的脚本设置--host 0.0.0.0
    // hostIp函数就全修改为本地ip服务了
    host: '0.0.0.0' || hostIp(),
    port: 8314, // 这个端口可以自己定义
    https: false, // https:{type:Boolean}配置前缀
    open: true, // 配置自动启动浏览器
    onAfterSetupMiddleware: mocksServer, // 开发环境mock数据
    proxy: {
      '/api': {
        target: 'https://api.taobao.cn/',
        changeOrigin: true,
        ws: true,
        secure: false,
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  }
});
